<?php
!function_exists('adminmsg') && die('Forbidden');

$cid = intval($cid);
require_once(D_P.'data/cache/cate.php');
if ($catedb[$cid]['mid']==-2 && $very['aggrebbs']){
	require_once(R_P.'require/class_bbs.php');
}elseif ($catedb[$cid]['mid']==-1 && $very['aggreblog']){
	require_once(R_P.'require/class_blog.php');
}


class Category{
	/* 对栏目进行操作的类 */
	var $complete; //栏目群体操作的结束标志
	var $catedb;
	var $moduledb;
	var $method;
	
	function __construct(){
		global $catedb,$moduledb,$very;
		$this->catedb = $catedb;
		$this->moduledb = $moduledb;
	}
	
	function Category(){
		$this->__construct();
	}
	
	function doIt(){
		global $action;
		!$action && $action='show';
		$this->method = $action;
		switch ($action){
			case 'show':
				$this->show($_GET['up']);
				break;
			case 'add':
				$this->add();
				break;
			case 'edit':
				$this->edit();
				break;
			case 'del':
				$this->del();
				break;
			case 'taxis':
				$this->taxis();
				break;
			case 'total':
				$this->total();
				break;
			case 'filetotal':
				$this->fileTotal();
				break;
			case 'publist':
				$this->publist();
				break;
			case 'pubview':
				$this->pub();
				break;
			case 'pubupdate':
				$this->pub();
				break;
			case 'viewlist':
				$this->viewList();
				break;
			case 'selectTpl':
				$this->selectTpl();
				break;
			case 'pubindex':
				require_once(R_P.'require/class_action.php');
				$op = new Action('pubindex');
				$op->doIt();
				adminmsg('operate_success');
				break;
			default:
				Showmsg('undefined_request');
				break;	
		}
	}
	
	protected function show($cid=''){ //显示栏目结构
		global $db,$basename;
		if($cid){
			$cname=$this->catedb[$cid]['cname'];
			$sql="WHERE up='$cid'";
		}else{
			$cname='ROOT';
			$sql="WHERE up=0";
		}
		$rs=$db->query("SELECT * FROM cms_category $sql ORDER BY taxis DESC");
		$categorydb = array();
		while ($tree = $db->fetch_array($rs)){
			$tree['up']=$tree['up'] ? $this->catedb[$tree[up]]['cname'] : '------';
			$tree['module']=$this->moduledb[$tree['mid']]['mname'];
			$categorydb[] = $tree;
		}
		require PrintEot('header');
		require PrintEot('category');
		adminbottom();
	}
	
	protected function add()
	{ //添加新栏目
		global $action,$step,$up,$checks,$basename,$very;
		if(!$step)
		{
			$mod_select='';
			foreach ($this->moduledb as $key=>$m){
				if(!$very['aggrebbs'] && $key==-2) continue;
				if(!$very['aggreblog'] && $key==-1) continue;
				$mod_select.= "<option value=\"$key\">$m[mname]</option>";
			}		
			require_once(R_P.'require/class_cate.php');
			$cate = new Cate();
			$cate_select = $cate->tree();
			if($up){
				if($this->catedb[$up]['link']) Showmsg('cate_linkadd');
				$mid = $up_mod=$this->catedb[$up]['mid'];
				$mod_select=str_replace("value=\"$up_mod\"","value=\"$up_mod\" selected",$mod_select);
				$cate_select=str_replace("value=\"$up\"","value=\"$up\" selected",$cate_select);
				//$ifchange="disabled=\"readonly\"";
			}else{
				$mid = 1; //default
				$mod_select=str_replace("value=\"1\"","value=\"1\" selected",$mod_select);
			}
			require_once(R_P.'require/fckeditor/fckeditor.php');
			$e = new FCKeditor('description');
			$e->ToolbarSet = 'Basic';
			$e->Height=120;
			$e->Width=320;
			$description_input = $e->CreateHtml();
		
			$bbsinfo['digest'] = $autopub = $comment = $display = $htmlpub = $listpub = 1;
			$bbsinfo['viewtype'] = 0;
			ifcheck($bbsinfo['digest'],'ifdigest');
			ifcheck($bbsinfo['viewtype'],'viewtype');
			ifcheck($htmlpub,'htmlpub');
			ifcheck($listpub,'listpub');
			ifcheck($autopub,'autopub');
			ifcheck($comment,'comment');
			ifcheck(1, 'guestview');
			$type_1 = 'checked';
			extract($checks);
			
			$groupSelect = $this->getGroupSelect();
			$serverSelect = $this->getServerSelect();
			require PrintEot('header');
			require PrintEot('category');
			adminbottom();
		}
		elseif ($step==2)
		{
			$this->saveCate();
			require_once(R_P.'require/class_cache.php');
			$cache = new Cache();
			$cache->cate();
			$cid = mysql_insert_id();
			$cache->singleCate($cid);
			if($mid && $_POST['listpub'])
			{
				$refreshto = "$admin_file?adminjob=category&cid=$cid&action=publist";
				$msg = "cate_autopublist";
			}
			else 
			{
				$refreshto = "$admin_file?adminjob=content&action=view&cid=$cid";
				$msg = "cate_addok";
			}
			operate($msg,$refreshto);
		}		
	}
	
	/**
	 * 编辑栏目
	 *
	 */
	function edit()
	{ //编辑栏目
		global $db,$basename,$action,$step,$checks,$cid,$very;
		$cateinfo = $db->get_one("SELECT * FROM cms_category WHERE cid='$cid'");
		if(!$step)
		{
			@extract($cateinfo,EXTR_SKIP);
			$groupSelect = $this->getGroupSelect(explode(',', $groupids));
			$serverSelect = $this->getServerSelect($serverid);
			
			if(!empty($mid)){
				$mod_name = $this->moduledb[$mid]['mname'];
				$mod_select = "<option value=\"$mid\" selected>$mod_name</option>";
			}
			if($very['aggrebbs'] && $mid=='-2'){
				$bbsinfo=unserialize($addtion);
				ifcheck($bbsinfo['viewtype'],'viewtype');
				ifcheck($bbsinfo['digest'],'ifdigest');
				ifcheck($bbsinfo['taxis'],'taxis');
			}elseif ($very['aggreblog'] && $mid=='-1'){
				$bloginfo=unserialize($addtion);
				ifcheck($bloginfo['viewtype'],'viewtype');
				ifcheck($bloginfo['digest'],'ifdigest');
				ifcheck($bloginfo['taxis'],'taxis');			
			}
			$ifchange = "disabled=\"disabled\"";
			ifcheck($htmlpub,'htmlpub');
			ifcheck($autopub,'autopub');
			ifcheck($listpub,'listpub');
			ifcheck($comment,'comment');
			ifcheck($guestview, 'guestview');
			$d = 'type_'.$type;
			$$d = 'checked';
			//ifcheck($display,'display');
			extract($checks);
			require_once(D_P.'data/cache/cate.php');
			require_once(R_P.'require/class_cate.php');
			$cate = new Cate();
			$cate_select = $cate->tree();
			$cate_select = str_replace("value=\"$up\"","value=\"$up\" selected",$cate_select);
			require_once(R_P.'require/fckeditor/fckeditor.php');
			$e = new FCKeditor('description');
			$e->ToolbarSet = 'Basic';
			$e->Height=120;
			$e->Width=320;
			$e->Value=$description;
			$description_input = $e->CreateHtml();
			require PrintEot('header');
			require PrintEot('category');
			adminbottom();
		}
		elseif ($step==2)
		{
			$this->saveCate();
			require_once(R_P.'require/class_cache.php');
			$cache = new Cache();
			$cache->cate();
			$cache->singleCate($cid);
			//如果动态改为静态，则需要重置所有内容为未发布
			if($_POST['filepath']!=$cateinfo['filepath'] && $cateinfo['filepath']){
				rename(R_P.$very['htmdir'].'/'.$cateinfo['filepath'],R_P.$very['htmdir'].'/'.$_POST['filepath']);
				//如果遇到更名，则更名
			}
			if($cateinfo['htmlpub'] == 0 && $_POST['htmlpub'] == 1 && $_POST['oldmodule']>0){
				$db->update("UPDATE cms_category SET new=total WHERE cid='$cid'");
				require_once(D_P.'data/cache/cate.php');
				$mid = $this->catedb[$cid]['mid'];
				$db->update("UPDATE cms_contentindex SET ifpub=0 WHERE cid='$cid'");
				operate('cate_needpuball',"$admin_file?adminjob=content&action=view&cid=$cid");			
			}else{
				operate('cate_editok',"$admin_file?adminjob=content&action=view&cid=$cid");
			}
		}
	}
	
	/**
	 * 目录的存储过程
	 *
	 */
	protected function saveCate()
	{
		global $db,$action,$up,$very,$user_tplpath;
		extract($_POST,EXTR_SKIP);
		$sqladd ='';
		empty($cname) && Showmsg('cate_nocname');
		if($action=='edit' && $oldmodule) $mid = $oldmodule;
		if($up){
			$this->catedb[$up]['link'] && Showmsg('cate_linkadd');
			if($cid == $up)
			{
				Showmsg('cate_uperror');
			}
			//$this->catedb[$up]['mid']!=$mid && Showmsg('cate_differentmid'); //子栏目必须和上级栏目内容模型保持一致
		}
		if($mid==0 || $oldmodule==0)
		{ //外部调用
			empty($link) && Showmsg('cate_nolink');
			$link = Char_cv($link);
			$sqladd = ",link='$link',addtion=''";
			$mid = 0; //如果是外部调用,mid设置为0
		}
		elseif ($mid=='-2')
		{ //BBS调用
			if (!$very['aggrebbs']) {
				Showmsg('mod_aggrebbs');
			}
			if($bbsinfo['fid'] && !ereg("^[0-9,]+$",$bbsinfo['fid'])) Showmsg('cate_fiderror');
			$addtion = addslashes(serialize($bbsinfo));
			$sqladd = ",link='',addtion='$addtion'";
		}
		elseif ($mid=='-1')
		{ //Blog调用
			if (!$very['aggreblog']) {
				Showmsg('mod_aggreblog');
			}
			if($bloginfo['fid'] && !ereg("^[0-9,]+$",$bloginfo['fid'])) Showmsg('cate_fiderror');
			$addtion = addslashes(serialize($bloginfo));
			$sqladd = ",link='',addtion='$addtion'";
		}
		else 
		{
			$sqladd = ",link='',addtion=''";
		}
		
		$cname = Char_cv($cname);
		$path = Char_cv($path);
		$tpl_index = Char_cv($tpl_index);
		$tpl_content = Char_cv($tpl_content);
		$file_index = Char_cv($file_index);
		$file_content = Char_cv($file_content);
		$metakeyword = Char_cv($metakeyword);
		$metadescrip = Char_cv($metadescrip);
		$depth = $up ? $this->catedb[$up]['depth']+1 : 1;
		$serverid = intval($_POST['serverid']);
		$guestview = intval($_POST['guestview']);
		
		$groupids = array();
		foreach ($_POST['groupids'] as $groupid)
		{
			$groupids[] = intval($groupid);
		}
		$groupids = implode(',', $groupids);
		if($tpl_index && !file_exists($user_tplpath.'/'.$tpl_index)) Showmsg('cate_tplpatherror');
		if($tpl_content && !file_exists($user_tplpath.'/'.$tpl_content)) Showmsg('cate_tplpatherror');
		
		if(!$cid){
			$rs = $db->get_one("SELECT MAX(cid) as id FROM cms_category");
			$cid = $rs['id']+1;
		}
		if (substr($path,-1) == '/') {
			Showmsg('cate_patherror');
		}
		if($type){ //不发布的栏目不需以下操作
			if($path){
				$filepath = $path.'/';
			}else {
				$filepath = $cid.'/';
			}
/*			if($listpub && $htmlpub){
				if(!is_dir(R_P.$very['htmdir'].'/'.$filepath)){
					mkdir(R_P.$very['htmdir'].'/'.$filepath);
					chmod(R_P.$very['htmdir'].'/'.$filepath,0777);
					@fclose(@fopen(R_P.$very['htmdir'].'/'.$filepath.'/index.html', 'w'));
					@chmod(R_P.$very['htmdir'].'/'.$filepath.'/index.html', 0777);
				}
			}*/
			if($listpub){
				$listurl = $filepath.'index.'.$very['htmext'];
			}else{
				$listurl = '';
			}
		}
		
		/**
		 * RMS系统中的特殊设置
		 */
		$type = 1; //类型永远为1
		$autopub = 1; //永远是自动发布的
		$htmlpub = 0;
		$autoupdate = 0;
		$listpub = 0;
		
		
		$sql = "cms_category SET
			cname='$cname',
			mid='$mid',
			up='$up',
			depth='$depth',
			path='$path',
			htmlpub='$htmlpub',
			listpub='$listpub',
			autopub='$autopub',
			comment='$comment',
			listurl='$listurl',
			autoupdate='$autoupdate',
			type='$type',
			description='$description',
			tpl_index='$tpl_index',
			tpl_content='$tpl_content',
			file_index='$file_index',
			file_content='$file_content',
			metakeyword='$metakeyword',
			metadescrip='$metadescrip',
			groupids='$groupids',
			serverid='$serverid',
			guestview='$guestview'
			$sqladd
		";
		
		if($action == 'add')
		{
			$sql = "INSERT INTO ".$sql.",cid='$cid'";
		}
		elseif ($action == 'edit')
		{
			$sql = "UPDATE ".$sql. "WHERE cid='$cid'";
		}
		$db->update($sql);
	}
	
	function taxis($taxis){ //栏目排序
		global $db,$taxis;
		foreach ($taxis as $key=>$value){
			if(!is_numeric($value)){
				$value=(int)$value;
			}
			$db->update("UPDATE cms_category SET taxis='$value' WHERE cid='$key'");
		}
		require_once(R_P.'require/class_cache.php');
		$cache = new Cache();
		$cache->cate();
		operate('operate_success');
	}
	
	function total(){ //栏目统计
		global $db;
		foreach ($this->catedb as $cid=>$v){
			if($v['mid']<=0){
				$db->update("UPDATE cms_category SET total=0,new=0 WHERE cid='$cid'");
				continue;
			}else{
				//$table = 'cms_content'.$v['mid'];
				$rs1 = $rs2 = array();
				$rs1 = $db->get_one("SELECT COUNT(*) AS count FROM cms_contentindex WHERE cid='$cid'");
				$rs2 = $db->get_one("SELECT COUNT(*) AS count FROM cms_contentindex WHERE cid='$cid' AND ifpub=0");
				$db->update("UPDATE cms_category SET total=$rs1[count],new=$rs2[count] WHERE cid='$cid'");
			}
		}
		require_once(R_P . 'require/class_cache.php');
		Cache::writeCache('cate');
		adminmsg('cate_total');
	}
	
	function publist(){ //发表分类首页
		global $cid;
		require_once(R_P.'require/class_action.php');
		$op = new Action('publist');
		$op->cate($cid);
		$op->doIt();
		adminmsg('cate_publistok');
	}
	
	function pub(){
		global $action,$cid,$db,$step,$basename,$admin_file;
		!$step && $step=1;
		$tids = $this->getTids($cid,$step);
		require_once(R_P.'require/class_action.php');
		$op = new Action($action);
		$op->cate($cid);
		$op->doIt($tids);
		if($this->complete){
			adminmsg('cate_pubcomplete',"$admin_file?adminjob=content&cid=$cid&action=view");
		}else{
			$step++;
			adminmsg('cate_pubcontinue',"$basename&action=$action&cid=$cid&step=$step");
		}
	}
	
	function del(){
		global $db,$cid,$action;
		$rs = $db->get_one("SELECT COUNT(*) AS count FROM cms_category WHERE up='$cid'");
		$rs['count']>0 && Showmsg('cate_delchildfirst');
		unset($rs);
		$mid = $this->catedb[$cid]['mid'];
		if($mid>0){
			$tids = $this->getTids($cid,$step);
			if(count($tids)>0){
				require_once(R_P.'require/class_action.php');
				$op = new Action('delete');
				$op->cate($cid);
				$op->doIt($tids);
			}else{
				$this->complete = 1;
			}
			if($this->complete){
				$db->update("DELETE FROM cms_category WHERE cid='$cid'");
				require_once(R_P.'require/class_cache.php');
				$cache = new Cache();
				$cache->cate();
				$cache->delCate($cid);
				operate('cate_pubcomplete');
			}else{
				$step++;
				adminmsg('cate_pubcontinue',"$basename&action=$action&step=$step");
			}
		}else{
			$db->update("DELETE FROM cms_category WHERE cid='$cid'");
			require_once(R_P.'require/class_cache.php');
			$cache = new Cache();
			$cache->cate();
			$cache->delCate($cid);
			operate('operate_success');
		}
	}
	
	function viewList(){ //查看列表首页
		global $very;
		$cid = intval($_GET['cid']);
		if($this->catedb[$cid]['listpub']){
			$jumpurl = $very['url'].'/'.$this->catedb[$cid]['listurl'];
		}else{
			$jumpurl = "list.php?cid=$cid";
		}
		echo "<script language=\"javascript\">";
		echo "window.location='$jumpurl';";
		echo "</script>";
		exit();
	}
	
	function getTids($cid,$step)
	{ //根据步数来获取一段Tid进行操作
		global $db,$very;
		!$cid && Showmsg('data_error');
		$mid = $this->catedb[$cid]['mid'];
		(!$step || $step<=0) && $step=1;
		$opnum = $very['opnum'] ? intval($very['opnum']) : 50;
		$start = ($step-1)*$opnum;
		
		$bbsblogAction = array('publist','pubview','pubupdate');
		if($mid < 0 && !in_array($this->method,$bbsblogAction))
		{
			Showmsg('action_bbsorblog');
		}
		if($mid == -2){
			$cidInfo = unserialize(stripslashes($this->catedb[$cid]['addtion']));
			!$cidInfo['viewtype'] && Showmsg('action_bbsorblog');
			$bbs = new BBS();
			$this->bbs->cid = $cid;
			$bbs->readConfig($cidInfo);
			$rs = $bbs->getThread($start,$opnum);
			$tids = array();
			foreach ($rs as $val){
				$tids[] = $val['tid'];
			}
			unset($rs);
			$total = $bbs->total();
		}elseif ($mid == -1){
			Showmsg('action_bbsorblog'); //当前不对Blog内容在CMS内生成页面
		}else {
			$rt = $db->get_one("SELECT COUNT(*) AS total FROM cms_contentindex WHERE cid='$cid'");
			$total = $rt['total'];
			$rs = $db->query("SELECT tid FROM cms_contentindex WHERE cid='$cid' LIMIT $start,$opnum");
			$tids = array();
			while ($t = $db->fetch_array($rs)) {
				$tids[] = $t['tid'];
			}
		}
		$GLOBALS['total'] = $total;
		$GLOBALS['opnum'] = $opnum;
		if($start+$opnum>=$total){
			$this->complete = 1; //表示已经获取完毕
		}else{
			$this->complete = 0; //没有结束
		}
		return $tids;
	}
	
	function selectTpl()
	{ //为栏目选择模板
		global $user_tplpath,$direct,$basename,$inputname,$job;	
		require_once(R_P.'require/class_path.php');
		$p = new path(D_P.$user_tplpath);
		$p->viewurl = "$basename&action=selectTpl&inputname=$inputname&";
		$p->fileurl = "insertTpl";
		$p->setDir($direct);
		if($job=='up') $p->up();
		$files = $p->getDir();
		$direct = $p->currentpath;
		require PrintEot('header');
		require PrintEot('selecttpl');
		adminbottom(0);
	}
	
	protected function getGroupSelect($groupids = array())
	{
		include_once(D_P . 'data/cache/group.php');
		$selectString = '';
		foreach ($group as $key => $val)
		{
			$selectString .= "<div style='width:22%; float:left; padding:3px 0 2px 4px;'><input type='checkbox' name='groupids[]' value='$key' ";
			if (in_array($key, $groupids))
			{
				$selectString .= "Checked";
			}
			$selectString .= "/>$val[groupname] </div>";
		}
		return $selectString;
	}
	
	protected function getServerSelect($serverid = 0)
	{
		include_once(D_P . 'data/cache/server.php');
		$selectString = '<select name="serverid">';
		$selectString .= '<option value="0">默认存储点</option>';
		
		foreach ($server as $key => $val)
		{
			$selectString .= "<option value='$key' ";
			if ($key == $serverid)
			{
				$selectString .= "selected";
			}
			$selectString .= ">$val[servername] </option>";			
		}
		$selectString .= '</select>';
		
		return $selectString;
	}
	
	protected function fileTotal()
	{
		global $db,$basename;
		if (!isset($_GET['limit']) || !isset($_GET['id']))
		{
			$id = 0;
			$rs = $db->get_one("SELECT COUNT(*) AS total FROM cms_contentindex");
			$limit = $rs['total'];
			$id = 1;
		}
		else 
		{
			$limit = intval($_GET['limit']);
			$id = intval($_GET['id']); 
		}
		
		$id < 1 && $id = 1;
		$start = $id-1;
		$rs = $db->get_array("SELECT tid FROM cms_contentindex LIMIT $start,50"); //一次100条内容
		foreach ($rs as $r)
		{
			$tid = $r['tid'];
			//$username = $r['username'];
			//$rt = $this->db->get_one("select count(*) as total from cms_resource r left join cms_contentindex i using(tid) where i.publisher='$username' AND r.delflag=0");
			$rt = $db->get_one("select count(*) as total from cms_resource where tid='$tid' AND delflag=0");
			$db->query("UPDATE cms_contentindex SET resnum=$rt[total] WHERE tid=$tid");
		}
		//echo $id;exit;
		$id += 50;
		$start = $id - 1;
		if ($id >= $limit)
		{
			adminmsg('全部重新统计完成', $basename);
		}
		else 
		{
			adminmsg('统计了' . $start  . '个内容，共计' . $limit . '个内容，现在自动进入下一步', $basename . '&action=filetotal&id=' . $id . '&limit=' . $limit);
		}
	}
}

$cate = new Category();
$cate->doIt();
?>